<template>
    <div>
        <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
        <!-- 提示警告区 -->
        <el-alert
            title="编辑商品信息"
            type="info"
            center
            show-icon
            :closable="false">
        </el-alert>
        <!-- 步骤条 -->
            <!-- 此处减0是把string转化为number -->
        <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>
        <!-- tab区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
            <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="befroeTabLeave" @tab-click="tabClicked">
                <el-tab-pane label="基本信息">
                    <el-form-item label="商品名称" prop="goods_name">
                        <el-input v-model="addForm.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="goods_price">
                        <el-input v-model="addForm.goods_price" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品重量" prop="goods_weight">
                        <el-input v-model="addForm.goods_weight" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="goods_number">
                        <el-input v-model="addForm.goods_number" type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="goods_cat">
                        <el-cascader
                        v-model="addForm.goods_cat"
                        :options="cateList"
                        :props="cateProp"
                        @change="handleChange"
                        disabled>
                        </el-cascader>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数">
                    <!-- 渲染表单的item项 -->
                    <el-form-item :label="item.attr_name" v-for="item in manyTabData" :key="item.attr_id">
                        <!-- 复选框组 -->
                        <el-checkbox-group v-model="item.attr_vals">
                            <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品属性">
                    <el-form-item :label="item.attr_name" v-for="item in onlyTabData" :key="item.attr_id">
                        <el-input v-model="item.attr_vals"></el-input>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片">
                    <el-upload
                        :headers="headerObj"
                        :action="uploadUrl"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        list-type="picture"
                        :on-success="handleSuccess"
                        :file-list="addForm.pics">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容">
                    <!-- 富文本编辑器 -->
                    <quill-editor v-model="addForm.goods_introduce"></quill-editor>
                    <el-button type="primary" class="addBtn" @click="addBtn">添加商品</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog
    title="图片预览"
    :visible.sync="previewVisible"
    width="50%">
    <img :src="previewPath" alt="">
    </el-dialog>
    </div>
</template>

<script>
    import _ from 'lodash'
    export default {
        data() {
            return {
                // 步骤条的激活
                activeIndex:'0',
                // 编辑商品的表单对象
                addForm:{
                    goods_name:'',
                    goods_price:'',
                    goods_weight:'',
                    goods_number:'',
                    goods_cat:'', //商品所属分类
                    pics:[], //图片数组
                    goods_introduce:'', //商品介绍
                    attrs:[],
                },
                // 表单验证规则
                addFormRules:{
                    goods_name:[
                        {required:true,message:"请输入商品名称",trigger:"blur"}
                    ],
                    goods_price:[
                        {required:true,message:"请输入商品价格",trigger:"blur"}
                    ],
                    goods_weight:[
                        {required:true,message:"请输入商品重量",trigger:"blur"}
                    ],
                    goods_number:[
                        {required:true,message:"请输入商品数量",trigger:"blur"}
                    ],
                    goods_cat:[
                        {required:true,message:"请选择商品分类",trigger:"blur"}
                    ],
                },
                // 复选框v-model
                // 存放商品分类数据
                cateList:[],
                // 级联选择器的配置参数
                cateProp:{
                    label:'cat_name',
                    value:'cat_id',
                    children:'children',
                    expandTrigger: 'hover'
                },
                // 动态参数列表数据
                manyTabData:[],
                // 静态属性数据列表
                onlyTabData:[],
                // 上传图片的URL
                uploadUrl:'http://127.0.0.1:8888/api/private/v1/upload',
                // 图片上传的请求头
                headerObj:{Authorization:window.sessionStorage.getItem('token')},
                // 预览图片值
                previewPath:'',
                // 预览图片窗口控制
                previewVisible:false,
                // 接收list传过来的id
                goods_id:'',
            }
        },
        created() {
            // this.getCateList()
            // 取得goods传过来的id
            let id=this.$route.params.id
            if(id){
                window.sessionStorage.setItem('goods_id',id)
            }else{
                id=window.sessionStorage.getItem('goods_id')
                if(!id){ //没点击“编辑”，无ID
                    this.$message.error('无效编辑，即将返回商品列表页！')
                    let that=this
                    let timer=setTimeout(function(){
                        that.$router.push('/goods')
                        clearTimeout(timer)
                    },850)
                }
            }
            this.goods_id=id
            this.getCateListById()

            
        },
        methods: {
            // 根据id获取商品分类
            async getCateListById(){
                let {data:res}=await this.$http.get('goods/'+this.goods_id)
                if(res.meta.status!=200) return this.$message.error('获取商品分类失败！')
                this.addForm=res.data
                // this.handlePics() 接口存在问题
                console.log(res.data)
            },
            // 获取商品分类
            async getCateList(){
                let {data:res}=await this.$http.get('categories')
                if(res.meta.status!=200) return this.$message.error('获取商品分类失败！')
                this.cateList=res.data
            },
            // 级联选中时触发
            handleChange(){
                // 判断是否是有三级
                if(this.addForm.goods_cat.length!=3) this.addForm.goods_cat=[]
            },  
            // tab标签页切换事件
            befroeTabLeave(newTab,oldTab){
                let flag=1
                this.$refs.addFormRef.validate(val=>{
                    if(!val){
                        this.$message.error('请完善商品信息！')
                        flag=false
                    }
                })
                if(!flag) { //此处这样写去解决在validate中return false无效问题，不要使用异步
                    return false
                }
            },
            // 点击tab时触发面板切换，获得activeIndex
            tabClicked(){
                // 动态参数面板
                    this.manyTabData=[]
                    this.onlyTabData=[]
                    // 分割字符串为数组，作为动态参数面板的多选参数
                    this.addForm.attrs.forEach(item=>{
                        if(item.attr_sel=='many'){
                            if(typeof(item.attr_vals)=='string' && item.attr_vals.length){
                                item.attr_vals=item.attr_vals.split(' ')
                            }
                            this.manyTabData.push(item)
                        }else if(item.attr_sel=='only'){ //排除空字符串
                            this.onlyTabData.push(item)
                        }
                    })
            },
            // 处理已加载的图片
            handlePics(){
                let pics=this.addForm.pics
                for(let i=0;i<pics.length;i++){
                let pics=this.addForm.pics
                    let picsInfo={name:pics.pics_id,url:pics[i]}
                    this.addForm.pics.push(picsInfo)
                }
                console.log(this.addForm.pics)
            },
            // 处理图片预览效果
            handlePreview(file){
                this.previewPath=file.response.data.url
                this.previewVisible=true
            },
            // 移除图片操作
            handleRemove(file){
                // 获取将要删除的图片的临时路径
                let filePath=file.response.data.tmp_path
                // 从pics数组中找到该图索引
                let i=this.addForm.pics.findIndex(x=>{
                    x.pic==filePath
                })
                // 使用splice方法删除
                this.addForm.pics.splice(i,1)
                this.$message.success('删除图片成功！')
                console.log(this.addForm.pics)
            },
            // 图片上传成功
            handleSuccess(file){
                // 拼接一个图片的信息对象（临时路径）
                let picInfo={pic:file.data.tmp_path}
                // 将信息对象添加到数组中
                this.addForm.pics.push(picInfo)
                this.$message.success('上传图片成功！')
            },
            // 添加新商品
            async addBtn(){
                // goods_cat用“,”进行分割为字符串
                    /*此处写法会报错，级联使用的是数组
                     this.addForm.goods_cat=this.addForm.goods_cat.join(',')
                      使用lodash的cloneDeep深拷贝方法  
                    */ 
                   let form=_.cloneDeep(this.addForm)
                   form.goods_cat=form.goods_cat.join(',')
                // 处理动态参数和静态属性
                    this.manyTabData.forEach(item=>{//动态
                        let newInfo={attr_id:item.attr_id,attr_value:item.attr_vals.join(' ')}
                        this.addForm.attrs.push(newInfo)
                    })
                    this.onlyTabData.forEach(item=>{//静态
                        let newInfo={attr_id:item.attr_id,attr_value:item.attr_vals}
                        this.addForm.attrs.push(newInfo)
                    })
                    form.attrs=this.addForm.attrs
                // 发起请求添加商品
                    let {data:res}=await this.$http.post('goods',form)
                    if(res.meta.status!=201) return this.$message.error('添加商品失败！'+res.meta.msg)
                    this.$message.success('添加商品成功！')
                    this.$router.push('/goods')
            },
        },
        computed: {
            // 计算级联选择的内容是否为3级
            cateId(){
                if(this.addForm.goods_cat.length==3) return this.addForm.goods_cat[2]
                return null
            }
        },
    }
</script>

<style scoped>
.el-checkbox{margin: 0 10px 0 0;}
img{width: 100%;height: 100%;}
.addBtn{margin-top: 15px;}
</style>